# -*- coding: utf-8 -*-
import sys

sys.path.append('../..')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests, json
from common.helper import Helper
from urllib.parse import urlencode
from threading import Thread


class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "爱心守护神长期意外险"

    # 生成产品数据
    def genProductInfo(self):
        plan = {
            "planA": {
                # 年龄段
                "year": [str(i) for i in range(0, 10)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["200000", "300000"],
                # 保障期限
                "days": ["20y", "30y", "70s", "80s", "zs"],
                # 交费间隔
                "interval": ["5", "10", "20", "30"],
                # 交通意外
                "common_traffic": ["0", "1"]
            },
            "planB": {
                # 年龄段
                "year": [str(i) for i in range(10, 18)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["200000", "300000", "500000", "600000", "800000"],
                # 保障期限
                "days": ["20y", "30y", "70s", "80s", "zs"],
                # 交费间隔
                "interval": ["5", "10", "20", "30"],
                # 交通意外
                "common_traffic": ["0", "1"]
            },
            "planC": {
                # 年龄段
                "year": [str(i) for i in range(18, 41)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["500000", "600000", "800000", "1200000", "1500000", "2000000"],
                # 保障期限
                "days": ["20y", "30y", "70s", "80s", "zs"],
                # 交费间隔
                "interval": ["5", "10", "20", "30"],
                # 交通意外
                "common_traffic": ["0", "1"]
            },
            "planD": {
                # 年龄段
                "year": [str(i) for i in range(41, 51)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["500000", "600000", "800000", "1200000"],
                # 保障期限
                "days": ["20y", "30y", "70s", "80s", "zs"],
                # 交费间隔
                "interval": ["5", "10", "20"],
                # 交通意外
                "common_traffic": ["0", "1"]

            },
            "planE": {
                # 年龄段
                "year": [str(i) for i in range(51, 61)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["500000", "600000", "800000", "1200000"],
                # 保障期限
                "days": ["20y", "30y", "70s", "80s", "zs"],
                # 交费间隔
                "interval": ["5", "10"],
                # 交通意外
                "common_traffic": ["0", "1"]

            }

        }

        for k in plan:
            for v in product(plan[k]["year"], plan[k]["gender"], plan[k]["money"], plan[k]["days"], plan[k]["interval"],
                             plan[k]["common_traffic"]):
                data = Helper.formatProductInfo(plan[k], v)
                self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(**data))
                self.mysql._conn.commit()
                print(domain[self.name]["insert_sql"].format(**data))

    # 执行爬虫
    def requestJson(self, dt=None, mysql=None):
        data = {
            "openid": "******************",
            "mainRiskCode": "DTIB02",
            "addRiskCode": "DTIB02",
            "mainRiskAmnt": str(int(int(dt["money"]) / 10000)),
            "addRiskAmnt": str(int(int(dt["money"]) / 10000)),
            "insuYear": "1000" if dt["days"] == "zs" else dt["days"].replace("y", "") if "y" in dt["days"] else dt[
                "days"].replace("s", ""),
            "payEndYear": dt["interval"],
            "sex": "0" if dt["gender"] == "M" else "1",
            "birthday": "{0}-01-01".format(str(2020 - int(dt["year"]))),
            "dutytype": "1" if dt["common_traffic"] == "0" else "2",
            "sign": "********************",
            "productCode": "YWX"
        }
        print(data)
        payload = urlencode(data).replace("+", "")
        r = requests.post(url=domain[self.name]["url"], headers=domain[self.name]["header"], data=payload, verify=False)
        if r.status_code == 200 and "standPrem" in r.text:

            price = r.json()["object"]["standPrem"]
            data = {
                "name": self.name,
                "id": dt["id"],
                "price": price
            }
            print(data)
            mysql.updatePrice(data)
        else:
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 3
            }
            mysql.updateTask(data)
            print("\n/*产品价格信息更新失败:%d*/" % dt["id"])

    def startProcess(self):
        threads = []
        for i in range(3):
            mysql = MysqlClient()
            t = Thread(target=Helper.runProcess, args=(mysql, self.name, self.requestJson,))
            t.start()
            threads.append(t)
        for t in threads:
            t.join()
